package com.bamboo.tool.template.export.view.dialog;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.math.MathUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import com.bamboo.tool.config.BambooToolComponent;
import com.bamboo.tool.config.RestfulCloudApplicationCache;
import com.bamboo.tool.db.SqliteConfig;
import com.bamboo.tool.entity.ApiClass;
import com.bamboo.tool.entity.QueryClassParameter;
import com.bamboo.tool.template.export.entity.ExportApi;
import com.bamboo.tool.template.export.entity.ExportDirectory;
import com.bamboo.tool.template.export.enums.ExportFileType;
import com.bamboo.tool.template.export.enums.ExportModel;
import com.bamboo.tool.template.export.util.ExportConversionUtil;
import com.bamboo.tool.util.FileGenerationUtil;
import com.bamboo.tool.util.TaskUtil;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import org.apache.commons.io.FilenameUtils;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.io.File;
import java.sql.Array;
import java.util.*;

public class ExportDialogWrapper extends DialogWrapper {

    private JPanel mainPanel;
    private TextFieldWithBrowseButton outputDirectory;
    private JComboBox fileTypeComboBox;
    private JComboBox exportComboBox;

    private Project project;
    private QueryClassParameter queryClassParam;
    private FileChooserDescriptor myFileDescriptor;

    public ExportDialogWrapper(QueryClassParameter queryClassParam, Project project) {
        super(false);
        init();
        this.myFileDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
        this.project = project;
        this.queryClassParam = queryClassParam;
        outputDirectory.addBrowseFolderListener("导出地址", "选择要导出的文件地址", project, myFileDescriptor);

        String defaultPath = RestfulCloudApplicationCache.getExportDefaultPath();
        boolean exist = FileUtil.exist(defaultPath);
        if (!exist) {
            FileUtil.mkdir(defaultPath);
        }

        Arrays.stream(ExportFileType.values()).forEach(fileTypeComboBox::addItem);
        Arrays.stream(ExportModel.values()).forEach(exportComboBox::addItem);
        outputDirectory.setText(defaultPath);
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        return mainPanel;
    }

    @Override
    protected void doOKAction() {
        TaskUtil.run(project, "Restful Cloud 导出", () -> {
            Collection<ApiClass> apiClass = BambooToolComponent.getStoreService().getApiClass(queryClassParam);
            Map<String, List<ExportDirectory>> exportDirectory = ExportConversionUtil.toExportDirectory(apiClass);
            ExportFileType exportFileType = (ExportFileType) fileTypeComboBox.getSelectedItem();
            ExportModel exportModel = (ExportModel) exportComboBox.getSelectedItem();

            String outputDirectoryPath = outputDirectory.getText() + "\\" + DateUtil.today() + "\\";
            FileUtil.mkdir(outputDirectoryPath);

            String osName = System.getProperty("os.name");
            if (osName.startsWith("Mac")) {
                RuntimeUtil.exec("sudo chmod -R 777 " + outputDirectoryPath);
            }else {
                File file = new File(outputDirectoryPath);
                boolean exists = file.exists();
                if (exists) {
                    file.setExecutable(true);
                    file.setReadable(true);
                    file.setWritable(true);
                }
            }
            if (ExportModel.SINGLE_METHOD.equals(exportModel)) {
                String finalOutputDirectoryPath = outputDirectoryPath;
                exportDirectory.values().stream().forEach(e -> {
                    if (CollUtil.isNotEmpty(e)) {
                        e.stream().forEach(a -> {
                            List<ExportApi> apis = a.getApis();
                            if (CollUtil.isNotEmpty(apis)) {
                                apis.stream().forEach(api -> {
                                    String outputPath = finalOutputDirectoryPath + api.getTitle() + "接口文档" + exportFileType.getFileSuffixName();
                                    outputPath = generateNotExistFileName(outputPath);
                                    ExportDirectory directory = new ExportDirectory();
                                    directory.getApis().add(api);
                                    directory.setExportModel(ExportModel.SINGLE_METHOD.getCode());
                                    FileGenerationUtil.generation(exportFileType.getTemplatePath(), exportFileType.getTemplateName(), outputPath, Arrays.asList(directory));
                                });
                            }

                        });
                    }
                });

            } else if (ExportModel.SINGLE_DIRECTORY.equals(exportModel)) {
                String finalOutputDirectoryPath = outputDirectoryPath;
                exportDirectory.values().stream().forEach(e -> {
                    if (CollUtil.isNotEmpty(e)) {
                        e.stream().forEach(a -> {
                            String outputPath = finalOutputDirectoryPath + a.getDirectoryTitle() + "接口文档" + exportFileType.getFileSuffixName();
                            outputPath = generateNotExistFileName(outputPath);
                            FileGenerationUtil.generation(exportFileType.getTemplatePath(), exportFileType.getTemplateName(), outputPath, Arrays.asList(a));
                        });
                    }
                });
            } else if (ExportModel.PROJECT_DIRECTORY.equals(exportModel)) {
                String finalOutputDirectoryPath = outputDirectoryPath;
                exportDirectory.values().stream().forEach(e -> {
                    if (CollUtil.isNotEmpty(e)) {

                        String outputPath = finalOutputDirectoryPath  + e.get(0).getProjectName() + "接口文档" + exportFileType.getFileSuffixName();
                        outputPath = generateNotExistFileName(outputPath);
                        FileGenerationUtil.generation(exportFileType.getTemplatePath(), exportFileType.getTemplateName(), outputPath, e);
                    }
                });

            } else if (ExportModel.ALL_METHOD.equals(exportModel)) {
                List<ExportDirectory> directors = new ArrayList<>();
                exportDirectory.values().stream().forEach(e -> directors.addAll(e));

                outputDirectoryPath = outputDirectoryPath  + DateUtil.format(new Date(), "HHmmss") + "接口文档" + exportFileType.getFileSuffixName();
                String filePath = generateNotExistFileName(outputDirectoryPath);
                FileGenerationUtil.generation(exportFileType.getTemplatePath(), exportFileType.getTemplateName(), filePath, directors);
            }


        });
        super.doOKAction();
    }

    /**
     * 如果文件已存在 则自动重命名为带后缀的文件名
     */
    private static String generateNotExistFileName(String src) {
        String path = src;
        String extension = FilenameUtils.getExtension(path);
        boolean hasExtension = StrUtil.isNotBlank(extension);
        int i = 1;
        while (FileUtil.exist(path)) {
            if (hasExtension) {
                path = StrUtil.subBefore(path, ".", true);
            }
            boolean hasSuffix = path.contains("(") && path.endsWith(")");
            if (!hasSuffix) {
                path = path + "(" + i + ")";
                i++;
            } else {
                String suffix = StrUtil.subAfter(path, "(", true);
                path = StrUtil.subBefore(path, "(", true);
                final char c = suffix.charAt(0);
                final int integer = Convert.toInt(c) + 1;
                path = path + "(" + integer + ")";
            }
            path = path + "." + extension;

        }
        return path;
    }
}
